import xml.etree.ElementTree as ET
import json
import os
import sys

# precise_repo_xts = "ability_ability_base,arkui_napi"
precise_repo_xts = sys.argv[1]
home =  os.getcwd() + "/../../../"
acts_home = home + "test/xts/acts/"
manifest_home = home + ".repo/"
precise_gni_name = "precise_run.gni"

def getbundname (path_list):
    print (path_list)
    bundle_list = []
    for path in path_list:
        # 读取JSON文件并获取指定key的value
        with open(home+path+"/bundle.json", 'r') as file:
            data = json.load(file)
        bundle_list.append(data['component']['name'])
    return bundle_list

def getdepends(bundlelist):
    depends_list = bundlelist
    for root, dirs, files in os.walk(home):
        for file in files:
            if file == 'bundle.json':
                # 构建完整的文件路径
                file_path = os.path.join(root, file)
                # 读取 JSON 文件并转换为 Python 对象
                with open(file_path, 'r') as f:
                    json_data = json.load(f)
                    bundle_name = json_data['component']['name']
                    if "deps" not in json_data['component']:
                        continue
                    if "components" in json_data['component']['deps']:
                        components_defs =  json_data['component']['deps']['components']
                        if len([element for element in bundlelist if element in components_defs]) != 0 and bundle_name not in depends_list:
                            depends_list.append(bundle_name)
                    if "third_party_defs" in json_data['component']['deps']:
                        third_party_defs = json_data['component']['deps']['third_party']
                        if len([element for element in bundlelist if element in third_party_defs]) != 0 and bundle_name not in depends_list:
                            depends_list.append(bundle_name)
    return depends_list

def write_precise_gni(depends_list):
    # 将数组转换为字符串形式，例如使用逗号分隔
    array_str = json.dumps(depends_list)

    # 打开文件并写入数组字符串
    with open( acts_home + precise_gni_name, 'w') as file:
        file.write("precise_run=")
        file.write(array_str)

# def generate_dependency_tree(package, dependencies):
#     if package not in dependencies:
#         return {}
#
#     tree = {}
#     for dependency in dependencies[package]:
#         sub_tree = generate_dependency_tree(dependency, dependencies)
#         tree[dependency] = sub_tree
#
#     return tree
def run(precise_repo_xts_list):
    # 获取bundle_name_list
    bundlelist = getbundname(precise_repo_xts_list)
    print(bundlelist)
    # 获取全部需要跑的bundlename
    depends_list = getdepends(bundlelist)
    # depends_list = [
    #     "ffmpeg",
    #     "cast_engine",
    #     "build_framework",
    #     "liteos_m",
    #     "liteos_a",
    #     "runtime_core"
    # ],
    print(depends_list)
    # 写入gni文件
    write_precise_gni(depends_list)


if __name__ == '__main__':
    run(precise_repo_xts.split(':'))